package com.mall.b2c.template.directive;

import static com.mall.common.directive.DirectiveUtils.OUT_LIST;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.mall.b2c.hessian.CacheService;
import com.mall.common.directive.DirectiveUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * Created by lzx on 2015/5/5.
 */
@Repository
public class ArticleCategoryDirective extends BaseDirective{

    public static final String PARAM_CHANNEL_CODE = "parentCode";
    public static final String PARAM_IDS = "ids";
    public static final String PARAM_NUM = "num";

    @Resource
    private CacheService cacheService;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
        String parentCode = DirectiveUtils.getString(PARAM_CHANNEL_CODE, params);
        Integer num = DirectiveUtils.getInt(PARAM_NUM, params);
        Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
        paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(cacheService.getArticleCategory(parentCode, num)));
        Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
        body.render(env.getOut());
        DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);

    }

}
